<template>
  <div class="avatar-uploader avatar-cut-box">
    <a class="avatar-cut-btn">
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </a>
    <input
      ref="uploads"
      type="file"
      id="uploads"
      :accept="updateConfig.accept"
      @change="uploadImg($event, 1)"
    >
    <!-- <upload-cut ref="uploadcut" field="img" @src-file-set="srcFileSet" @crop-success="cropSuccess" v-model="show" :width="200" :height="200" :noRotate="false" img-format="png" :size="size"></upload-cut> -->
    <el-dialog
      title="图片裁剪"
      :visible.sync="show"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="false"
      width="40%"
    >
      <div
        class="flex-row flex-align-c"
        style="margin-bottom: 20px;"
      >
        <el-tag
          style="margin-left:10px;cursor: pointer;padding:0;"
          v-for="(tag,index) in fixedTagList"
          v-bind:key="index"
          :type="tag.active == 'true'?'success':''"
        >
          <span
            style="display:inline-block;padding:0 10px;heigth:100%;"
            @click="fixedChange(tag.name,tag.val,index)"
          >{{tag.name}}</span>
        </el-tag>
      </div>
      <section style="height: 400px;">
        <VueCropper
          ref="cropper"
          :img="updateConfig.img"
          :autoCrop="updateConfig.autoCrop"
          :autoCropWidth="updateConfig.autoCropWidth"
          :autoCropHeight="updateConfig.autoCropHeight"
          :outputSize="updateConfig.size"
          :outputType="updateConfig.outputType"
          :info="updateConfig.info"
          :canScale="updateConfig.canScale"
          :full="updateConfig.full"
          :canMove="updateConfig.canMove"
          :canMoveBox="updateConfig.canMoveBox"
          :fixedBox="updateConfig.fixedBox"
          :fixed="updateConfig.fixed"
          :original="updateConfig.original"
          :fixedNumber="updateConfig.fixedNumber"
          @realTime="realTime"
        ></VueCropper>

        <!-- <div class="show-preview" :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '5px'}">
            <div :style="previews.div">
              <img :src="updateConfig.img" :style="previews.img">
            </div>
          </div> -->
      </section>
      <div
        slot="footer"
        class="flex-row flex-align-c flex-justify-b dialog-footer"
      >
        <div class="flex-row flex-align-c flex-justify-a">
          <el-button
            type="primary"
            size="mini"
            @click="changeScale(1)"
          ><i class="el-icon-circle-plus-outline"></i></el-button>
          <el-button
            type="primary"
            size="mini"
            @click="changeScale(-1)"
          ><i class="el-icon-remove-outline"></i></el-button>
          <el-button
            type="primary"
            size="mini"
            @click="rotateLeft"
          ><i class="el-icon-arrow-left"></i></el-button>
          <el-button
            type="primary"
            size="mini"
            @click="rotateRight"
          ><i class="el-icon-arrow-right"></i></el-button>
        </div>
        <div class="flex-row flex-align-c flex-justify-b">
          <el-button @click="show = false;">取 消</el-button>
          <el-button
            type="primary"
            @click="cropSuccess"
          >确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import defaultConfig from './utils/config'
export default {
  mixins: [defaultConfig.mixins],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    },
    saveEvt: {
      type: Function,
      'default': null
    },
    saveChangeEvt: {
      type: Function,
      'default': null
    }
  },
  data() {
    return {
      previews: {},
      show: false,
      fixedTagList: defaultConfig.fixedTagList,
      fileName: ''
    }
  },
  watch: {
    show: {
      handler(newData, oldData) {
        if (typeof oldData !== 'undefined') {
          this.output(newData)
        }
      },
      immediate: true
    }
  },
  components: {
    VueCropper
  },
  mounted() {

  },
  methods: {
    toggleShow() {
      this.show = !this.show
    },
    realTime(data) {
      this.previews = data
    },
    fixedChange(name, type, index) {
      this.$refs.cropper.clearCrop()
      if (type === 'auto') {
        this.updateConfig.fixed = false
      } else {
        this.updateConfig.fixed = true
        this.updateConfig.fixedNumber = type
      }

      this.fixedTagList.map((item, key) => {
        item.active = key === index ? 'true' : 'false'
      })

      this.$nextTick(() => {
        this.$refs.cropper.goAutoCrop()
      })
    },
    uploadImg(e, num) {
      const file = e.target.files[0]
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: '图片类型必须是.gif,jpeg,jpg,png,bmp中的一种!',
          type: 'error'
        })
        return false
      }
      this.fileName = file.name || `${new Date().getTime()}uploadimg.${file.type}`
      const reader = new FileReader()
      reader.onload = (e) => {
        let data = 'base64'
        if (typeof e.target.result === 'object') {
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        if (num === 1) {
          this.config.img = data
        } else if (num === 2) {
          this.example2.img = data
        }
      }
      reader.readAsDataURL(file)
      this.$refs.uploads.value = ''
      this.toggleShow()
    },
    changeScale(num = 1) {
      this.$refs.cropper.changeScale(num)
    },
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    cropSuccess() {
      this.$refs.cropper.getCropData((data) => {
        const _file = this.dataURLtoFile(data, this.fileName)
        this.createFile(_file)
      })
    },
    dataURLtoFile(dataurl, filename) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    createFile(fdata) {
      const blobPath = URL.createObjectURL(fdata)
      const uid = new Date().getTime()
      const filename = fdata.name
      const fildData = {
        name: filename,
        percentage: 0,
        raw: {},
        showCheck: false,
        size: 0,
        status: 'ready',
        uid: uid,
        url: blobPath
      }
      fildData.raw = fdata
      this.fileName = ''
      this.saveout(fildData)
      this.toggleShow()
    },
    output() {
      if (
        Object.prototype.toString.call(this.changeEvt) === '[object Function]'
      ) {
        this.changeEvt(this.show)
      }
    },
    saveout(fildData) {
      if (
        Object.prototype.toString.call(this.changeEvt) === '[object Function]'
      ) {
        this.saveEvt(fildData)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$a_w: 100px;
.avatar-cut-box {
  width: $a_w;
  height: $a_w;
  cursor: pointer;
  #uploads {
    position: relative;
    clip: rect(0 0 0 0);
    filter: Alpha(opacity=0);
    -moz-opacity: 0;
    opacity: 0;
    width: $a_w;
    height: $a_w;
    z-index: 2;
    cursor: pointer;
  }
  .avatar-cut-btn {
    position: absolute;
    display: inline-block;
    z-index: 1;
    width: 100%;
    height: 100%;
  }
}
</style>
